local H = require "packages/new_heg/util"
local HC = require "packages/new_hegcomplements/util"
local U = require "packages/utility/utility"
local extension = Package:new("main")
extension.extensionName = "new_hegcomplements"
extension.game_modes_whitelist = { 'ex_heg_mode', 'mul_heg_mode' }

Fk:loadTranslationTable {
  ["main"] = "官正",
  ["ce_hc_heg"] = "国典",
  ["nos_hc_heg"] = "旧",
  ["le_hc_heg"] = "限定",
}

local huangzhong = General(extension, "ce_hc_heg__n_huangzhong", "shu", 4)

local liegong = fk.CreateTriggerSkill{
  name = "ce_hc__liegong",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self)) then return end
    return data.card.trueName == "slash" and player.room:getPlayerById(data.to).hp >= player.hp
  end,
  on_cost = function (self, event, target, player, data)
    local choices = {"ce_hc__liegong-damage::"..data.to, "ce_hc__liegong-disresponsive::"..data.to , "Cancel"}
    local room = player.room
    local choice = room:askForChoice(player, choices, self.name,"#ce_hc__liegong::"..data.to)
    if choice ~= "Cancel" then
      self.cost_data = choice
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if self.cost_data:startsWith("ce_hc__liegong-damage") then
      data.additionalDamage = (data.additionalDamage or 0) + 1
      player.room:sendLog{
        type = "#ce_hc__liegong-damage",
        from = player.id,
        to =  {data.to},
        toast = true,
      }
    else
      data.disresponsiveList = data.disresponsiveList or {}
      table.insert(data.disresponsiveList, data.to)
      player.room:sendLog{
        type = "#ce_hc__liegong-disresponsive",
        from = player.id,
        to =  {data.to},
        toast = true,
      }
    end
  end,
}

local liegong_range = fk.CreateAttackRangeSkill{
  name = "#ce_hc__liegong_range",
  correct_func = function(self, from, to)
    if from:hasShownSkill(liegong.name) then
      for _, p in ipairs(Fk:currentRoom().alive_players) do
        if string.find(p.general, "lord") and p:hasSkill("shouyue") and p.kingdom == from.kingdom then
          return 1
        end
      end
    end
    return 0
  end,
}

local liegong_targetmod = fk.CreateTargetModSkill{
  name = "#ce_hc__liegong_targetmod",
  bypass_distances =  function(self, player, skill, card, target)
    if skill.trueName == "slash_skill" and player:hasShownSkill(liegong.name) then
      return card and target and target:getHandcardNum() <= player:getHandcardNum()
    end
  end,
}
liegong:addRelatedSkill(liegong_range)
liegong:addRelatedSkill(liegong_targetmod)
huangzhong:addSkill(liegong)
huangzhong:addCompanions("hs__n_weiyan")

Fk:loadTranslationTable{
  ["ce_hc_heg__n_huangzhong"] = "黄忠",
  ["#ce_hc_heg__n_huangzhong"] = "老当益壮",
  ["illustrator:ce_hc_heg__n_huangzhong"] = "凡果",
  ["ce_hc__liegong"] = "烈弓",
  [":ce_hc__liegong"] = "你对手牌数不大于你的角色使用【杀】无距离关系的限制。当你于使用【杀】指定一个目标后，若其体力值不小于你，你可以选择一项：1.令此【杀】对其造成的伤害+1；2.令其不能使用【闪】响应此【杀】。",

  ["ce_hc__liegong-damage"]="此【杀】对 %dest 的伤害+1",
  ["ce_hc__liegong-disresponsive"]="此【杀】不可被 %dest 响应",
  ["#ce_hc__liegong"]="烈弓：你可令此【杀】对 %dest 造成的伤害+1，或令 %dest 不能响应此【杀】",
  ["#ce_hc__liegong-damage"]="%from 选择此【杀】对 %to 的伤害+1",
  ["#ce_hc__liegong-disresponsive"]="%from 选择此【杀】不可被 %to 响应",

  ["$ce_hc__liegong1"] = "弓不离手，自有转机。",
  ["$ce_hc__liegong2"] = "箭阵开道，所向无敌。",
  ["~ce_hc_heg__n_huangzhong"] = "把我的弓，拿来，呃……",
}

local menghuo = General(extension, "ce_hc_heg__n_menghuo", "shu", 4)

local zaiqi = fk.CreateTriggerSkill{
  name = "ce_hc__zaiqi",
  anim_type = "support",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Discard then
      local room = player.room
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
      if turn_event == nil then return false end
      local x = 0
      room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.DiscardPile then
            for _, info in ipairs(move.moveInfo) do
              if Fk:getCardById(info.cardId).color == Card.Red then
              x = x + 1
              end
            end
          end
        end
        return false
      end, turn_event.id)
      if x > 0 then
        self.cost_data = x
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local x = self.cost_data
    local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, x,
    "#ce_hc__zaiqi-choose:::"..x, self.name, true)
    if #tos > 0 then
      room:sortPlayersByAction(tos)
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(self.cost_data.tos, Util.Id2PlayerMapper)
    for _, p in ipairs(targets) do
      if not p.dead then
        local choices = {"ce_hc__zaiqi_draw"}
        if player and not player.dead and player:isWounded() then
          table.insert(choices, "ce_hc__zaiqi_recover:"..player.id)
        end
        local choice = room:askForChoice(p, choices, self.name, "#ce_hc__zaiqi-choice:"..player.id)
        if choice == "ce_hc__zaiqi_draw" then
          p:drawCards(1, self.name)
        else
          room:recover({
            who = player,
            num = 1,
            recoverBy = p,
            skillName = self.name
          })
        end
      end
    end
  end,
}
local huoshou = fk.CreateTriggerSkill{
  name = "ce_hc__huoshou",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.PreCardEffect, fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and data.card.trueName == "savage_assault" then
      if event == fk.PreCardEffect then
        return player.id == data.to
      else
        return target ~= player and data.firstTarget
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.PreCardEffect then
      return true
    else
      data.extra_data = data.extra_data or {}
      data.extra_data.huoshou = player.id
    end
  end,

  refresh_events = {fk.PreDamage},
  can_refresh = function(self, event, target, player, data)
    if data.card and data.card.trueName == "savage_assault" then
      local e = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
      if e then
        local use = e.data[1]
        return use.extra_data and use.extra_data.huoshou
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local e = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if e then
      local use = e.data[1]
      data.from = room:getPlayerById(use.extra_data.huoshou)
    end
  end,
}
menghuo:addCompanions("hs__n_zhurong")
menghuo:addSkill(huoshou)
menghuo:addSkill(zaiqi)
Fk:loadTranslationTable{
  ["ce_hc_heg__n_menghuo"] = "孟获",
  ["#ce_hc_heg__n_menghuo"] = "南蛮王",
  ["illustrator:ce_hc_heg__n_menghuo"] = "废柴男",

  ["ce_hc__huoshou"] = "祸首",
  [":ce_hc__huoshou"] = "锁定技，【南蛮入侵】对你无效；当其他角色使用【南蛮入侵】指定目标后，你代替其成为此牌造成的伤害的来源。",

  ["ce_hc__zaiqi"] = "再起",
  [":ce_hc__zaiqi"] = "弃牌阶段结束时，你可令至多X名与你势力相同的角色各选择：1.摸一张牌；2.令你回复1点体力（X为本回合内置入弃牌堆的<font color='red'>红色</font>牌数）。",
  ["#ce_hc__zaiqi-choose"] = "再起：选择至多%arg名与你势力相同的角色，这些角色各选择摸一张牌或令你回复1点体力",

  ["#ce_hc__zaiqi-choice"] = "再起：选择摸一张牌或令%src回复1点体力",
  ["ce_hc__zaiqi_draw"] = "摸一张牌",
  ["ce_hc__zaiqi_recover"] = "令%src回复体力",
  
  ["$ce_hc__huoshou1"] = "背黑锅我来，送死？你去！",
  ["$ce_hc__huoshou2"] = "通通算我的！",
  ["$ce_hc__zaiqi1"] = "丞相助我！",
  ["$ce_hc__zaiqi2"] = "起！",
  ["~ce_hc_heg__n_menghuo"] = "七纵之恩……来世……再报了……",

}

local xushu = General(extension, "ce_hc_heg__n_xushu", "shu", 4)
xushu.deputyMaxHpAdjustedValue = -1
xushu:addCompanions("hs__n_zhaoyun")
xushu:addCompanions("hs__n_wolong")

local qiance = fk.CreateTriggerSkill{
  name = "ce_hc__qiance",
  anim_type = "control",
  events = {fk.TargetSpecified},
  can_trigger = function (self, event, target, player, data)
    return H.compareKingdomWith(target, player) and player:hasSkill(self) and data.firstTarget and data.card:isCommonTrick() and (player:hasShownSkill(self) or player == target)
      and table.find(AimGroup:getAllTargets(data.tos), function(p) return H.isBigKingdomPlayer(player.room:getPlayerById(p)) end)
  end,
  on_cost = function (self, event, target, player, data)
    if player.room:askForSkillInvoke(target, self.name) then
      local targets = table.filter(AimGroup:getAllTargets(data.tos), function(p) return H.isBigKingdomPlayer(player.room:getPlayerById(p)) end)--按发动前确定目标吧
      self.cost_data = {tos = targets}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = self.cost_data.tos
    local usedata = room.logic:getCurrentEvent():findParent(GameEvent.UseCard).data[1]
    if #targets > 0 then
      usedata.disresponsiveList = usedata.disresponsiveList or {}
      for _, p in ipairs(targets) do
        table.insertIfNeed(usedata.disresponsiveList, p)
      end
    end
  end,
}

local jujian = fk.CreateTriggerSkill{
  name = "ce_hc__jujian",
  anim_type = "big",
  relate_to_place = "d",
  frequency = Skill.Compulsory,
  events = {fk.EnterDying},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) and H.compareKingdomWith(player, target) and target.hp < 1 and not target.dead then
      self.cost_data = {tos = {target.id}}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:recover({
      who = target,
      num = math.min(1, target.maxHp) - target.hp,
      recoverBy = player,
      skillName = self.name,
    })
    if player:getMark("@@ce_hc__jujian_transform") == 0 then
      room:setPlayerMark(player,"@@ce_hc__jujian_transform", 1)
      H.transformGeneral(room, player)
    end
  end,
}

xushu:addSkill(qiance)
xushu:addSkill(jujian)

Fk:loadTranslationTable{
  ["ce_hc_heg__n_xushu"] = "徐庶",
  ["#ce_hc_heg__n_xushu"] = "难为完臣",
  ["illustrator:ce_hc_heg__n_xushu"] = "YanBai",

  ["ce_hc__qiance"] = "谦策",
  [":ce_hc__qiance"] = "当与你势力相同的角色使用锦囊牌指定目标后，其可令目标角色中的所有大势力角色不能响应此牌。",
  ["ce_hc__jujian"] = "举荐",
  [":ce_hc__jujian"] = "副将技，锁定技，此武将牌上减少1个单独的阴阳鱼。当与你势力相同的角色进入濒死状态时，你令其将体力回复至1点，然后你变更副将。",

  ["@@ce_hc__jujian_transform"]="举荐 已变更",

  ["$ce_hc__qiance1"] = "吾有良策，退敌解围。",
  ["$ce_hc__qiance2"] = "依某之计，万无一失。",
  ["$ce_hc__jujian1"] = "得此贤士，如鱼得水。",
  ["$ce_hc__jujian2"] = "将军，在下可举荐一人。",
  ["~ce_hc_heg__n_xushu"] = "未尽孝道，抱憾此生。",
}

local zongyu = General(extension, "ce_hc_heg__zongyu", "shu", 3)

local qiao = fk.CreateTriggerSkill{
  name = "ce_hc__qiao",
  anim_type = "control",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      not player.room:getPlayerById(data.from):isNude() and player:usedSkillTimes(self.name, Player.HistoryTurn) < 2
      and not H.compareKingdomWith(player.room:getPlayerById(data.from), player)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#ce_hc__qiao-invoke::"..data.from)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local from = room:getPlayerById(data.from)
    local id = room:askForCardChosen(player, from, "he", self.name)
    room:throwCard({id}, self.name, from, player)
    if not player:isNude() then
      room:askForDiscard(player, 1, 1, true, self.name, false)
    end
  end,
}

local chengshang = fk.CreateTriggerSkill{
  name = "ce_hc__chengshang",
  anim_type = "control",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.tos and
      table.find(TargetGroup:getRealTargets(data.tos), function(id)
        return not H.compareKingdomWith(player.room:getPlayerById(id), player) and not player.room:getPlayerById(id):isNude() end)
      and not data.damageDealt and player.room:getCurrent() and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(TargetGroup:getRealTargets(data.tos), function(id)
      return not H.compareKingdomWith(player.room:getPlayerById(id), player) and not player.room:getPlayerById(id):isNude() end)
    if #targets > 0 then
      local tos = room:askForChoosePlayers(player, targets, 1, 1, data.card.suit == Card.NoSuit and "#ce_hc__chengshang-invoke-nosuit" or
        ("#ce_hc__chengshang-invoke:::" .. data.card:getSuitCompletedString(true)), self.name)
        if #tos > 0 then
          self.cost_data = {tos = tos}
          return true
        end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    
    local to = room:getPlayerById(self.cost_data.tos[1])
    local prompt = data.card.suit == Card.NoSuit and "#ce_hc__chengshang-give-nosuit::" .. player.id
      or ("#ce_hc__chengshang-give::" .. player.id .. ":" .. data.card:getSuitCompletedString(true))
    local cards = room:askForCard(to, 1, 1, false, self.name, false, ".", prompt)
    local card, same = Fk:getCardById(cards[1]), false
    if data.card.suit ~= Card.NoSuit and not player.dead and data.card.number == card.number and data.card.suit == card.suit then
      same = true
    end
    room:obtainCard(player, cards, true, fk.ReasonGive)
    if same then
      room:handleAddLoseSkills(player, "-" .. self.name, nil, true, false)  --FIXME:被暗置会恢复技能，等主服修
    end
  end
}

zongyu:addSkill(qiao)
zongyu:addSkill(chengshang)

Fk:loadTranslationTable{
  ["ce_hc_heg__zongyu"] = "宗预",
  ["#ce_hc_heg__zongyu"] = "九酝鸿胪",
  ["illustrator:ce_hc_heg__zongyu"] = "铁杵文化",

  ["ce_hc__qiao"] = "气傲",
  [":ce_hc__qiao"] = "每回合限两次，当你成为不是与你势力相同的角色使用牌的目标后，你可弃置其一张牌，然后你弃置一张牌。",
  ["ce_hc__chengshang"] = "承赏",
  [":ce_hc__chengshang"] = "每回合限一次，当你使用指定有与你势力不同或未确定势力角色为目标的牌结算后，若此牌未造成伤害，你可以令其中一名目标角色交给你一张牌，"..
  "若此牌与你此次使用的牌花色点数均相同，你失去此技能。",

  ["#ce_hc__qiao-invoke"] = "气傲：你可以弃置 %dest 一张牌，然后你弃置一张牌",
  ["#ce_hc__chengshang-invoke"] = "是否发动〖承赏〗，令其中一名目标角色交给你一张牌，若为 %arg ，你失去此技能",
  ["#ce_hc__chengshang-invoke-nosuit"] = "是否发动〖承赏〗，令其中一名目标角色交给你一张牌",
  ["#ce_hc__chengshang-give"] = "承赏；交给 %dest 一张牌，若为 %arg ，其失去〖承赏〗",
  ["#ce_hc__chengshang-give-nosuit"] = "承赏；交给 %dest 一张牌，",

  ["$ce_hc__qiao1"] = "吾六十何为不受兵邪？",
  ["$ce_hc__qiao2"] = "芝性骄傲，吾独不为屈。",
  ["$ce_hc__chengshang1"] = "嘉其抗直，甚爱待之。",
  ["$ce_hc__chengshang2"] = "为国鞠躬，必受封赏。",
  ["~ce_hc_heg__zongyu"] = "吾年逾七十，唯少一死耳……",
}

local yangwan = General(extension, "ce_hc_heg__yangwan", "shu", 3, 3,General.Female) -- 保留原本的前缀

local youyan = fk.CreateTriggerSkill{
  name = "ce_hc__youyan",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and player.room.current == player then
      local suits = {"spade", "club", "heart", "diamond"}
      local can_invoked = false
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard then
          if move.from == player.id then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                table.removeOne(suits, Fk:getCardById(info.cardId, true):getSuitString())
                can_invoked = true
              end
            end
          end
        end
      end
      return can_invoked and #suits > 0
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local suits = {"spade", "club", "heart", "diamond"}
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard then
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              table.removeOne(suits, Fk:getCardById(info.cardId, true):getSuitString())
            end
          end
        end
      end
    end
    if #suits > 0 then
      local show_num = 4
      local cards = room:getNCards(show_num)
      room:moveCards{
        ids = cards,
        toArea = Card.Processing,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        proposer = player.id
      }
      room:delay(1000)
      local to_get = table.filter(cards, function(id)
        return table.contains(suits, Fk:getCardById(id, true):getSuitString())
      end)
      if #to_get > 0 then
        room:obtainCard(player.id, to_get, true, fk.ReasonJustMove)
      end
      cards = table.filter(cards, function (id)
        return room:getCardArea(id) == Card.Processing
      end)
      if #cards > 0 then
        room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name)
      end
    end
  end,
}

---@param room Room
---@param player ServerPlayer
---@param add boolean
---@param isDamage boolean
local function handleZhuihuan(room, player, add, isDamage)
  local mark_name = isDamage and "ce_hc__zhuihuan-damage" or "ce_hc__zhuihuan-discard"
  room:setPlayerMark(player, "@@" .. mark_name, add and 1 or 0)
  room:handleAddLoseSkills(player, add and "#" .. mark_name or "-#" .. mark_name, nil, false, true)
end

local zhuihuan = fk.CreateTriggerSkill{
  name = "ce_hc__zhuihuan",
  anim_type = "defensive",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room.alive_players, Util.IdMapper), 1, 2, "#ce_hc__zhuihuan-choose", self.name, true, true)
    if #to > 0 then
      self.cost_data = to
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local tos = self.cost_data
    local choices = {"ce_hc__zhuihuan-damage::" ..tos[1], "ce_hc__zhuihuan-discard::" ..tos[1]}
    if #tos == 1 then
      local choice = room:askForChoice(player, choices, self.name)
      local target = room:getPlayerById(tos[1])
      if choice:startsWith("ce_hc__zhuihuan-damage") then
        handleZhuihuan(room, target, true, true)
      elseif choice:startsWith("ce_hc__zhuihuan-discard") then
        handleZhuihuan(room, target, true, false)
      end
    elseif #tos == 2 then
      local choice = room:askForChoice(player, choices, self.name)
      local target1 = room:getPlayerById(tos[1])
      local target2 = room:getPlayerById(tos[2])
      if choice:startsWith("ce_hc__zhuihuan-damage") then
        handleZhuihuan(room, target1, true, true)
        handleZhuihuan(room, target2, true, false)
      elseif choice:startsWith("ce_hc__zhuihuan-discard") then
        handleZhuihuan(room, target2, true, true)
        handleZhuihuan(room, target1, true, false)
      end
    end
  end,

  refresh_events = {fk.BuryVictim, fk.TurnStart, fk.Death},
  can_refresh = function (self, event, target, player, data)
    if event == fk.BuryVictim then
      return target:getMark("@@ce_hc__zhuihuan-damage") == 1 or target:getMark("@@ce_hc__zhuihuan-discard") == 1
    end
    if event == fk.TurnStart then
      return player:hasSkill(self) and target == player
    end
    if event == fk.Death then
      return player:hasSkill(self, false, true) and player == target
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart or event == fk.Death then
      for _, p in ipairs(room.alive_players) do
        if p:getMark("@@ce_hc__zhuihuan-damage") == 1 then
          handleZhuihuan(room, p, false, true)
        end
        if p:getMark("@@ce_hc__zhuihuan-discard") == 1 then
          handleZhuihuan(room, p, false, false)
        end
      end
    elseif target:getMark("@@ce_hc__zhuihuan-damage") == 1 then
      handleZhuihuan(room, target, false, true)
    elseif target:getMark("@@ce_hc__zhuihuan-discard") == 1 then
      handleZhuihuan(room, target, false, false)
    end
  end,
}

local zhuihuan_damage = fk.CreateTriggerSkill{
  name = "#ce_hc__zhuihuan-damage",
  anim_type = "offensive",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    handleZhuihuan(room, target, false, true)
    if data.from and not data.from.dead then
      room:damage{
        from = player,
        to = data.from,
        damage = 1,
        skillName = self.name,
      }
    end
    
  end,
}

local zhuihuan_discard = fk.CreateTriggerSkill{
  name = "#ce_hc__zhuihuan-discard",
  anim_type = "offensive",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    handleZhuihuan(room, target, false, false)
    if data.from and not data.from:isKongcheng() then
      room:askForDiscard(data.from, 2, 2, false, self.name, false)
    end
  end,
}

yangwan:addCompanions("hs__n_machao")
yangwan:addSkill(youyan)
yangwan:addSkill(zhuihuan)
Fk:addSkill(zhuihuan_damage)
Fk:addSkill(zhuihuan_discard)

Fk:loadTranslationTable{
  ["ce_hc_heg__yangwan"] = "杨婉",
  ["#ce_hc_heg__yangwan"] = "融沫之鲡",
  --["designer:yangwan"] = "",
  ["illustrator:ce_hc_heg__yangwan"] = "木美人",

  ["ce_hc__youyan"] = "诱言",
  [":ce_hc__youyan"] = "每回合限一次，当你的牌于你回合内因弃置而置入弃牌堆后，你可亮出牌堆顶四张牌，获得其中与此置入弃牌堆花色均不相同的牌。",
  ["ce_hc__zhuihuan"] = "追还",
  [":ce_hc__zhuihuan"] = "回合结束时，你可选择分配以下效果给至多两名角色直至你下回合开始："..
  "1.下一次受到伤害后，伤害来源弃置两张手牌；2.下一次受到伤害后，对伤害来源造成1点伤害。",
  ["#ce_hc__zhuihuan-choose"] = "追还：选择一至两名角色分配对应效果",

  ["@@ce_hc__zhuihuan-discard"] = "追还",
  ["@@ce_hc__zhuihuan-damage"] = "追还",
  ["#ce_hc__zhuihuan-discard"] = "追还",
  ["#ce_hc__zhuihuan-damage"] = "追还",
  ["ce_hc__zhuihuan-damage"] = "对 %dest 分配伤害效果",
  ["ce_hc__zhuihuan-discard"] = "对 %dest 分配弃牌效果",

  ["$ce_hc__youyan1"] = "诱言者，为人所不齿。",
  ["$ce_hc__youyan2"] = "诱言之弊，不可不慎。",
  ["$ce_hc__zhuihuan1"] = "伤人者，追而还之！",
  ["$ce_hc__zhuihuan2"] = "追而还击，皆为因果。",
  ["~ce_hc_heg__yangwan"] = "遇人不淑……",
}

local zhouyi = General(extension, "ce_hc_heg__zhouyi", "wu", 3,3,General.Female)
local zhukou = fk.CreateTriggerSkill{
  name = "ce_hc__zhukou",
  anim_type = "drawcard",
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self)) then return end
    local room = player.room
    if room.current and room.current.phase == Player.Play then
      local damage_event = room.logic:getCurrentEvent()
      if not damage_event then return false end
      local events = room.logic:getActualDamageEvents(1, function(e)
        return e.data[1].from == player
      end, Player.HistoryPhase)
      if #events > 0 and damage_event.id == events[1].id then
        local n = #room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
          return e.data[1].from == player.id
        end, Player.HistoryTurn)
        if n > 0 then
          self.cost_data = n
          return true
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data, "#ce_hc__zhukou:::" .. self.cost_data)
  end,
  on_use = function(self, event, target, player, data)
    local n = self.cost_data
    player:drawCards(math.min(5, n), self.name)
  end,
}

local duannian = fk.CreateTriggerSkill{
  name = "ce_hc__duannian",
  anim_type = "drawcard",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and not player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    player.room:throwCard(player:getCardIds("h"), self.name, player, player)
    if player.dead then return end
    player:drawCards(player.maxHp - player:getHandcardNum(), self.name)
  end,
}

local lianyou = fk.CreateTriggerSkill{
  name = "ce_hc__lianyou",
  anim_type = "support",
  events = {fk.Death},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self, false, true)
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players,  function(p)
      return not p:hasSkill(self) end), Util.IdMapper)
    if #targets > 0 then
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#ce_hc__lianyou-choose", self.name, true)
      if #to > 0 then
        self.cost_data = {tos = to}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = self.cost_data.tos[1]
    room:handleAddLoseSkills(room:getPlayerById(to), "ce_hc__xinghuo")
  end,
}

local xinghuo = fk.CreateTriggerSkill{
  name = "ce_hc__xinghuo",
  frequency = Skill.Compulsory,
  anim_type = "offensive",
  events = {fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.damageType == fk.FireDamage and data.from == player
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + 1
  end,
}

zhouyi:addSkill(zhukou)
zhouyi:addSkill(duannian)
zhouyi:addSkill(lianyou)
zhouyi:addRelatedSkill(xinghuo)

Fk:loadTranslationTable{
  ["ce_hc_heg__zhouyi"] = "周夷",
  ["#ce_hc_heg__zhouyi"] = "靛情雨黛",
  --["designer:ce_hc_heg__zhouyi"] = "韩旭",
  ["illustrator:ce_hc_heg__zhouyi"] = "Tb罗根",

  ["ce_hc__zhukou"] = "逐寇",
  [":ce_hc__zhukou"] = "当你于每回合的出牌阶段首次造成伤害后，你可摸X张牌（X为本回合你已使用的牌数且至多为5）。",
  ["ce_hc__duannian"] = "断念",
  [":ce_hc__duannian"] = "出牌阶段结束时，你可弃置所有手牌，然后将手牌摸至体力上限。",
  ["ce_hc__lianyou"] = "莲佑",
  [":ce_hc__lianyou"] = "当你死亡时，你可令一名其他角色获得“兴火”。",
  ["#ce_hc__lianyou-choose"] = "莲佑：选择一名角色，其获得“兴火”。",
  ["ce_hc__xinghuo"] = "兴火",
  [":ce_hc__xinghuo"] = "锁定技，当你造成火属性伤害时，你令此伤害+1。",

  ["#ce_hc__zhukou"] = "逐寇：你可摸 %arg 张牌",

  ["$ce_hc__zhukou1"] = "草莽贼寇，不过如此。",
  ["$ce_hc__zhukou2"] = "轻装上阵，利剑出鞘。",
  ["$ce_hc__duannian1"] = "断思量，莫思量。",
  ["$ce_hc__duannian2"] = "一别两宽，不负相思。",
  ["$ce_hc__xinghuo1"] = "莲花佑兴，业火可兴。",
  ["$ce_hc__xinghuo2"] = "昔日莲花开，今日红火燃。",
  ["~ce_hc_heg__zhouyi"] = "江水寒，萧瑟起……",
}

local lvbu = General(extension, "ce_hc_heg__n_lvbu", "qun", 5)
local wushuang = fk.CreateTriggerSkill{
  name = "ce_hc__wushuang",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified, fk.TargetConfirmed,fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then
      return false
    end
    if event == fk.TargetSpecified then
      return target == player and table.contains({ "slash", "duel" }, data.card.trueName)
    elseif event ==  fk.TargetConfirmed then
      return data.to == player.id and data.card.trueName == "duel"
    elseif event == fk.AfterCardTargetDeclared and data.card.trueName == "duel" and target == player and (not data.card:isVirtual() or #data.card.subcards == 0) then
      local targets = player.room:getUseExtraTargets(data, false, false)
      return #targets > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardTargetDeclared then
      local current_targets = TargetGroup:getRealTargets(data.tos)
      local targets = room:getUseExtraTargets(data, false, false)
      local tos = room:askForChoosePlayers(player, targets, 1, 2,
      "#ce_hc__wushuang-choose:::"..data.card:toLogString(), self.name, true)
      if #tos > 0 then
        self.cost_data = {tos = tos}
        return true
      end
    else
      self.cost_data = {tos = event == fk.TargetSpecified and {data.to} or {data.from}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.AfterCardTargetDeclared then
      table.insertTable(data.tos, table.map(self.cost_data.tos, function (p)
        return {p}
      end))
    else
      data.fixedResponseTimes = data.fixedResponseTimes or {}
      if data.card.trueName == "slash" then
        data.fixedResponseTimes["jink"] = 2
      else
        data.fixedResponseTimes["slash"] = 2
        data.fixedAddTimesResponsors = data.fixedAddTimesResponsors or {}
        table.insert(data.fixedAddTimesResponsors, (event == fk.TargetSpecified and data.to or data.from))
      end
    end
  end,
}
lvbu:addSkill(wushuang)
lvbu:addCompanions("hs__n_diaochan")
Fk:loadTranslationTable{
  ["ce_hc_heg__n_lvbu"] = "吕布",
  ["#ce_hc_heg__n_lvbu"] = "戟指中原",
  ["illustrator:ce_hc_heg__n_lvbu"] = "凡果",
  ["ce_hc__wushuang"] = "无双",
  [":ce_hc__wushuang"] = "锁定技，当你使用【杀】指定目标后，该角色需依次使用两张【闪】才能抵消此【杀】；当你使用【决斗】指定目标后，或成为【决斗】的目标后，该角色每次响应此【决斗】需依次打出两张【杀】；你使用非转化的【决斗】的目标上限+2。",
  ["#ce_hc__wushuang-choose"] = "无双：你可以为 %arg 增加至多两个目标",

  ["$ce_hc__wushuang1"] = "还有哪个敢挑战我！？",
  ["$ce_hc__wushuang2"] = "三个齐上，也不是我的对手！",
  ["~ce_hc_heg__n_lvbu"] = "我竟然输了？不可能！",
}

local zuoci = General(extension, "ce_hc_heg__n_zuoci", "qun", 3)

local function GetSoul(player, n)
  local room = player.room
  local generals = room:findGenerals(function () return true end, n)
  local mark = U.getPrivateMark(player, "&ce_hc__soul")
  table.insertTableIfNeed(mark, generals)
  U.setPrivateMark(player, "&ce_hc__soul", mark)
  if #player:getTableMark("ce_hc__yigui_cards") == 0 then
    room:setPlayerMark(player, "ce_hc__yigui_cards", U.getUniversalCards(room, "bt"))
  end
end

local jihun = fk.CreateTriggerSkill{
  name = "ce_hc__jihun",
  anim_type = "masochism",
  events = {fk.Damaged, fk.AfterDying},
  can_trigger = function(self, event, target, player, data)
    if event == fk.Damaged then
    return player:hasSkill(self) and target == player
    elseif event == fk.AfterDying then
      return player:hasSkill(self) and target and not target.dead and H.compareKingdomWith(target, player, true)
    end
  end,
  on_use = function(self, event, target, player, data)
    GetSoul(player, 1)
  end,
}

local function canbeTargetedbySoul(to, name)
  local kingdoms, general = {}, Fk.generals[name]
  if general then
    table.insertIfNeed(kingdoms, general.kingdom)
    if general.subkingdom then
      table.insertIfNeed(kingdoms, general.subkingdom)
    end
  end
  local tokingdom = to.kingdom
  if tokingdom == "wild" and (to:getMark("hasShownMainGeneral") == 0 or to:getMark("__heg_wild") == 0) then --如果野人没亮过主将or开局没选野心家，按原势力
    tokingdom = to:getMark("__heg_init_kingdom")
  end
  return tokingdom == "unknown" or table.contains(kingdoms, tokingdom)
end

local function getAvailableSoul(player)
  local souls = U.getPrivateMark(player, "&ce_hc__soul")
  if #souls == 0 then return {} end
  local players, availables = {}, {}
  local extra_data = player:getTableMark("ce_hc__yigui_extra_data")
  if extra_data.fix_targets then
    table.insertTableIfNeed(players, extra_data.fix_targets)
  elseif extra_data.must_targets then
    table.insertTableIfNeed(players, extra_data.must_targets)
  elseif extra_data.exclusive_targets then
    table.insertTableIfNeed(players, extra_data.exclusive_targets)
  elseif extra_data.include_targets then
    table.insertTableIfNeed(players, extra_data.include_targets)
  end
  if #players == 0 then
    players = Fk.currentRoom(player).alive_players
  else
    players = table.map(players, Util.Id2PlayerMapper)
  end
  for _, s in ipairs(souls) do
    if table.find(players, function (p) return canbeTargetedbySoul(p, s) end) then
      table.insert(availables, s)
    end
  end
  return availables
end

local function getAvailableYiguiCard(player, skill_name, card_names, souls)
  souls = souls or getAvailableSoul(player)
  card_names = card_names or table.map(player:getTableMark("ce_hc__yigui_cards"), function (id) return Fk:getCardById(id).name end)
  if #card_names == 0 then return {} end
  local ban_cards = player:getTableMark("ce_hc__yigui_useds-turn")
  table.insertTableIfNeed(ban_cards, {"jink", "nullification", "heg__nullification"})
  local extra_data = player:getTableMark("ce_hc__yigui_extra_data")
  local names = {}
  for _, name in ipairs(card_names) do
    local card = Fk:cloneCard(name)
    if (Fk.currentResponsePattern == nil or Exppattern:Parse(Fk.currentResponsePattern):match(card))
      and not table.contains(ban_cards, card.trueName) then
      card.skillName = skill_name
      for _, soul in ipairs(souls) do
        card:setMark("ce_hc__yigui", soul)
        if player:canUse(card, extra_data) and not player:prohibitUse(card) then
          local min_target = card.skill:getMinTargetNum()
          if min_target > 0 then
            for _, p in pairs(Fk.currentRoom(player).alive_players) do
              if card.skill:targetFilter(p.id, {}, {}, card, extra_data, player) then
                table.insertIfNeed(names, name)
                goto continue
              end
            end
          else
            table.insertIfNeed(names, name)
            goto continue
          end
        end
      end
    end
    ::continue::
  end
  return names
end

local yigui = fk.CreateViewAsSkill{
  name = "ce_hc__yigui",
  mute = true,
  pattern = ".|.|.|.|.|basic,trick",
  expand_pile = function(self, player)
    return player:getTableMark("ce_hc__yigui_cards")
  end,
  interaction = function(self, player)
    local souls = U.getPrivateMark(player, "&ce_hc__soul")
    local availables = getAvailableSoul(player)
    if #availables == 0 then return false end
    return HC.GeneralCardNameBox { choices = availables, all_choices = souls }
  end,
  card_filter = function(self, to_select, selected, player)
    if #selected > 0 or not table.contains(player:getTableMark("ce_hc__yigui_cards"), to_select) then return false end
    local name = Fk:getCardById(to_select).name
    local cardnames = getAvailableYiguiCard(player, self.name, {name}, {self.interaction.data})
    return table.contains(cardnames, name)
  end,
  view_as = function(self, cards)
    if #cards == 0 or not self.interaction.data then return end
    local name = Fk:getCardById(cards[1]).name
    local card = Fk:cloneCard(name)
    card.skillName = self.name
    card:setMark("ce_hc__yigui", self.interaction.data)
    return card
  end,
  enabled_at_play = function(self, player)
    return #getAvailableSoul(player) > 0
  end,
  enabled_at_response = function(self, player, response)
    return #getAvailableSoul(player) > 0 and not response and #getAvailableYiguiCard(player, self.name) > 0
  end,
}

local yigui_show = fk.CreateTriggerSkill{
  name = "#ce_hc__yigui_show",
  main_skill = yigui,
  events = {fk.GeneralRevealed},
  can_trigger = function(self, event, target, player, data)
    if target ~= player or not player:hasSkill(self.main_skill) or player:getMark("ce_hc__yigui_show") > 0 then return false end
    for _, v in pairs(data) do
      if table.contains(Fk.generals[v]:getSkillNameList(), yigui.name) then return true end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player:broadcastSkillInvoke(yigui.name)
    player.room:setPlayerMark(player, "ce_hc__yigui_show", 1)
    GetSoul(player, 2)
  end,

  refresh_events = { fk.HandleAskForPlayCard ,fk.PreCardUse},
  can_refresh = function(self, event, target, player, data)
    if #U.getPrivateMark(player, "&ce_hc__soul") == 0 then return false end
    if event == fk.HandleAskForPlayCard then
      return data.user == player
    elseif event == fk.PreCardUse then
      return player == target and table.contains(data.card.skillNames, yigui.name)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.PreCardUse then
      room:notifySkillInvoked(player, yigui.name)
      player:broadcastSkillInvoke(yigui.name)
      room:addTableMark(player, "ce_hc__yigui_useds-turn", data.card.trueName)
      local mark = U.getPrivateMark(player, "&ce_hc__soul")
      table.removeOne(mark, data.card:getMark("ce_hc__yigui"))
      room:returnToGeneralPile({data.card:getMark("ce_hc__yigui")})
      if #mark == 0 then
        room:setPlayerMark(player, "@[private]&ce_hc__soul", 0)
      else
        U.setPrivateMark(player, "&ce_hc__soul", mark)
      end
      room:sendLog{
        type = "#ce_hc__yigui-use",
        from = player.id,
        arg = data.card:getMark("ce_hc__yigui"),
        arg2 = data.card.name,
        toast = true,
      }
      data.extra_data = data.extra_data or {}
      data.extra_data.ce_hc__yigui = data.card:getMark("m_hc__yigui") -- 往extra_data里备份一份魂的信息，防止扇子杀变火杀后信息丢失
    else
      room:setPlayerMark(player, "ce_hc__yigui_extra_data", data.afterRequest and 0 or data.extraData)
    end
  end,

  on_lose = function (self, player, is_death)
    local room = player.room
    room:returnToGeneralPile(U.getPrivateMark(player, "&m_hc__soul"))
    room:setPlayerMark(player, "@[private]&ce_hc__soul", 0)
  end,
}

local yigui_prohibit = fk.CreateProhibitSkill{
  name = "#ce_hc__yigui_prohibit",
  frequency = Skill.Compulsory,
  is_prohibited = function(self, from, to, card)
    if card and table.contains(card.skillNames, yigui.name) then
      local general = card:getMark("ce_hc__yigui")
      if not general then -- 丢失魂信息则寻找备用信息
        if RoomInstance then
          local logic = RoomInstance.logic
          local event = logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
          if event then
            local use = event.data[1]
            if table.contains(use.card.skillNames, yigui.name) and use.card.name == card.name then
              use.extra_data = use.extra_data or {}
              general = use.extra_data.ce_hc__yigui
            end
          end
        end
      end
      return general and not canbeTargetedbySoul(to, general)
    end
  end,
}

yigui:addRelatedSkill(yigui_show)
yigui:addRelatedSkill(yigui_prohibit)
zuoci:addSkill(yigui)
zuoci:addSkill(jihun)
zuoci:addCompanions("ld__n_yuji")

Fk:loadTranslationTable{
  ["ce_hc_heg__n_zuoci"] = "左慈",
  ["#ce_hc_heg__n_zuoci"] = "鬼影神道",
  ["illustrator:ce_hc_heg__n_zuoci"] = "吕阳",

  ["#ce_hc__yigui_show"] = "役鬼",
  ["ce_hc__yigui"] = "役鬼",
  [":ce_hc__yigui"] = "当你首次明置此武将牌后，你将两张未加入游戏的武将牌扣置于武将牌上，称为“魂”；"..
  "每回合每种牌名限一次，你可以移去一张“魂”，视为使用一张基本牌或普通锦囊牌，此牌只能指定与此“魂”势力相同或未确定势力的角色为目标。<br>"..
  "<font color = 'gray'>判断目标角色的势力是否与“魂”相同与野心家身份牌无关。</font>",
  ["ce_hc__jihun"] = "汲魂",
  [":ce_hc__jihun"] = "当你受到伤害后或与你势力不同的角色进入濒死状态被救回后，你可以将一张未加入游戏的武将牌扣置加入到“魂”牌中。",

  ["@[private]&ce_hc__soul"] = "魂",
  ["#ce_hc__yigui-use"] = "%from 移去“魂”  %arg ，视为使用 %arg2",

  ["$ce_hc__yigui1"] = "百鬼众魅，自缚见形。",
  ["$ce_hc__yigui2"] = "来去无踪，众谓诡异。",
  ["$ce_hc__jihun1"] = "魂聚则生，魂散则弃。",
  ["$ce_hc__jihun2"] = "魂羽化游，以辅四方。",
  ["~ce_hc_heg__n_zuoci"] = "仙人之逝，魂归九天……",
}

local himiko = General(extension, "le_hc_heg__himiko", "qun", 3, 3, General.Female)

local guishu = fk.CreateViewAsSkill{
  name = "le_hc__guishu",
  pattern = "known_both,befriend_attacking",
  anim_type = "drawcard",
  handly_pile = true,
  interaction = function(self, player)
    local names = {}
    local all_choices = {"befriend_attacking", "known_both"}
    for _, name in ipairs(all_choices) do
      if player:getMark("_le_hc__guishu-turn") ~= name and player:canUse(Fk:cloneCard(name)) then
        table.insertIfNeed(names, name)
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names, all_choices = all_choices }
  end,
  card_filter = function(self, to_select, selected, player)
    return #selected == 0 and Fk:getCardById(to_select).suit == Card.Spade
      and table.contains(player:getHandlyIds(), to_select)
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or self.interaction.data == nil then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
  before_use = function(self, player, use)
    player.room:setPlayerMark(player, "_le_hc__guishu-turn", use.card.name)
  end
}

local yuanyuk = fk.CreateTriggerSkill{
  name = "le_hc__yuanyuk",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and not data.from.dead and not data.from:inMyAttackRange(target)
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage - 1
  end
}

himiko:addSkill(yuanyuk)
himiko:addSkill(guishu)


Fk:loadTranslationTable{
  ['le_hc_heg__himiko'] = '卑弥呼', -- 十年心版
  ["#le_hc_heg__himiko"] = "邪马台的女王",
  ["illustrator:le_hc_heg__himiko"] = "聚一_小道恩",
  --["designer:le_hc_heg__himiko"] = "淬毒",

  ["le_hc__guishu"] = "鬼术",
  [":le_hc__guishu"] = "出牌阶段，你可将一张♠手牌当【远交近攻】或【知己知彼】使用（不可与你此回合上一次以此法使用的牌相同）。",
  ["le_hc__yuanyuk"] = "远域",
  [":le_hc__yuanyuk"] = "锁定技，当你受到伤害时，若有伤害来源且你不在伤害来源的攻击范围内，此伤害-1。",

  ["$le_hc__guishu1"] = "契约已定！",
  ["$le_hc__guishu2"] = "准备好，听候女王的差遣了吗？",
  ["$le_hc__yuanyuk1"] = "是你，在召唤我吗？",
  ["$le_hc__yuanyuk2"] = "这片土地的人，真是太有趣了。",
  ["~le_hc_heg__himiko"] = "我还会从黄泉比良坂回来的……",
}

local xurong = General(extension, "le_hc_heg__xurong", "qun", 4)
local xionghuo = fk.CreateActiveSkill{
  name = "le_hc__xionghuo",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  prompt = "#le_hc__xionghuo-active",
  can_use = function(self, player)
    return player:getMark("@le_hc__baoli") > 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and to_select ~= Self.id and target:getMark("@le_hc__baoli") == 0 and H.compareKingdomWith(Self, target, true)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:removePlayerMark(player, "@le_hc__baoli", 1)
    room:addPlayerMark(target, "@le_hc__baoli", 1)
  end,
}
local xionghuo_record = fk.CreateTriggerSkill{
  name = "#le_hc__xionghuo_record",
  main_skill = xionghuo,
  anim_type = "offensive",
  events = {fk.GeneralRevealed, fk.DamageCaused, fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(xionghuo) then
      if event == fk.GeneralRevealed then
        if player:usedSkillTimes(xionghuo.name, Player.HistoryGame) == 0 then
          for _, v in pairs(data) do
            if table.contains(Fk.generals[v]:getSkillNameList(), xionghuo.name) then return true end
          end
        end
      elseif event == fk.DamageCaused then
        return target == player and data.to ~= player and data.to:getMark("@le_hc__baoli") > 0 and data.card and data.to:getMark("@@le_hc__baoli_damage-turn") == 0
      else
        return target ~= player and target:getMark("@le_hc__baoli") > 0 and target.phase == Player.Play
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("le_hc__xionghuo")
    if event == fk.GeneralRevealed then
      room:addPlayerMark(player, "@le_hc__baoli", 3)
    elseif event == fk.DamageCaused then
      room:doIndicate(player.id, {data.to.id})
      data.damage = data.damage + 1
      room:setPlayerMark(data.to, "@@le_hc__baoli_damage-turn", 1)
    else
      room:doIndicate(player.id, {target.id})
      room:setPlayerMark(target, "@le_hc__baoli", 0)
      local rand = math.random(1, target:isNude() and 2 or 3)
      if rand == 1 then
        room:damage {
          from = player,
          to = target,
          damage = 1,
          damageType = fk.FireDamage,
          skillName = "le_hc__xionghuo",
        }
        if not (player.dead or target.dead) then
          room:addTableMark(target, "le_hc__xionghuo_prohibit-turn", player.id)
        end
      elseif rand == 2 then
        room:loseHp(target, 1, "le_hc__xionghuo")
        if not target.dead then
          room:addPlayerMark(target, "MinusMaxCards-turn", 1)
        end
      else
        local cards = table.random(target:getCardIds(Player.Hand), 1)
        table.insertTable(cards, table.random(target:getCardIds(Player.Equip), 1))
        room:obtainCard(player, cards, false, fk.ReasonPrey)
      end
    end
  end,

  refresh_events = {fk.BuryVictim, fk.EventLoseSkill},
  can_refresh = function(self, event, target, player, data)
    if event == fk.BuryVictim then
      return player == target and player:hasSkill(xionghuo, true, true) and table.every(player.room.alive_players, function (p)
        return not p:hasSkill(xionghuo, true)
      end)
    elseif event == fk.EventLoseSkill then
      return player == target and data == xionghuo and table.every(player.room.alive_players, function (p)
        return not p:hasSkill(xionghuo, true)
      end)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if p:getMark("@le_hc__baoli") > 0 then
        room:setPlayerMark(p, "@le_hc__baoli", 0)
      end
    end
  end,
}
local xionghuo_prohibit = fk.CreateProhibitSkill{
  name = "#le_hc__xionghuo_prohibit",
  is_prohibited = function(self, from, to, card)
    return card.trueName == "slash" and table.contains(from:getTableMark("le_hc__xionghuo_prohibit-turn") ,to.id)
  end,
}

xionghuo:addRelatedSkill(xionghuo_record)
xionghuo:addRelatedSkill(xionghuo_prohibit)
xurong:addSkill(xionghuo)

Fk:loadTranslationTable{
  ["le_hc_heg__xurong"] = "徐荣",
  ["#le_hc_heg__xurong"] = "玄菟战魔",
  ["cv:le_hc_heg__xurong"] = "曹真",
  --["designer:le_hc_heg__xurong"] = "Loun老萌",
  ["illustrator:le_hc_heg__xurong"] = "青岛磐蒲",

  ["le_hc__xionghuo"] = "凶镬",
  [":le_hc__xionghuo"] = "①当你首次明置此武将牌后，你获得三枚“暴戾”标记。②出牌阶段，你可以交给一名与你势力不同的角色一枚“暴戾”标记。③每回合每名角色限一次，当你使用牌对拥有“暴戾”标记的其他角色造成伤害时，此伤害+1。④拥有“暴戾”标记的其他角色出牌阶段开始时，其移去“暴戾”标记并随机执行：1.你对其造成1点火焰伤害，其本回合不能对你使用【杀】；2.其失去1点体力且本回合手牌上限-1；3.你获得其装备区里的一张牌，然后获得其一张手牌。",

  ["#le_hc__xionghuo_record"] = "凶镬",
  ["@le_hc__baoli"] = "暴戾",
  ["#le_hc__xionghuo-active"] = "发动 凶镬，将“暴戾”交给其他角色",
  ["@@le_hc__baoli_damage-turn"] = "凶镬 已造伤",

  ["$le_hc__xionghuo1"] = "战场上的懦夫，可不会有好结局！",
  ["$le_hc__xionghuo2"] = "用最残忍的方式，碾碎敌人！",
  ["~le_hc_heg__xurong"] = "死于战场……是个不错的结局……",
}


local lvlingqi = General(extension, "ce_hc_heg__lvlingqi", "qun", 4, 4, General.Female)
lvlingqi.mainMaxHpAdjustedValue = -1

local zhuangrong = fk.CreateActiveSkill{
  name = "ce_hc__zhuangrong",
  anim_type = "offensive",
  card_num = 1,
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected, player)
    local card = Fk:getCardById(to_select)
    return #selected == 0 and card.type == Card.TypeTrick and not player:prohibitDiscard(to_select)
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, from, from)
    if from.dead then return end
    room:setPlayerMark(from, "@@ce_hc__zhuanrong_hs_wushuang-phase", 1)
    room:handleAddLoseSkills(from, "ce_hc__wushuang_zr", nil)
    room.logic:getCurrentEvent():findParent(GameEvent.Phase):addCleaner(function()
      room:handleAddLoseSkills(from, "-ce_hc__wushuang_zr", nil, true, false)
    end)
  end,
}

local shenwei = fk.CreateTriggerSkill{
  name = "ce_hc__shenwei",
  relate_to_place = "m",
  anim_type = "drawcard",
  events = {fk.DrawNCards},
  --frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw and
      table.every(player.room.alive_players, function(p) return player.hp >= p.hp end)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    data.n = data.n + 2
  end,
}

local shenwei_maxcards = fk.CreateMaxCardsSkill{
  name = "#ce_hc__shenwei_maxcards",
  correct_func = function(self, player)
    if player:hasShownSkill(shenwei) then
      return 2
    end
  end
}

local wushuangZR = fk.CreateTriggerSkill{
  name = "ce_hc__wushuang_zr",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified, fk.TargetConfirmed,fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then
      return false
    end
    if event == fk.TargetSpecified then
      return target == player and table.contains({ "slash", "duel" }, data.card.trueName)
    elseif event ==  fk.TargetConfirmed then
      return data.to == player.id and data.card.trueName == "duel"
    elseif event == fk.AfterCardTargetDeclared and data.card.trueName == "duel" and target == player and (not data.card:isVirtual() or #data.card.subcards == 0) then
      local targets = player.room:getUseExtraTargets(data, false, false)
      return #targets > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardTargetDeclared then
      local current_targets = TargetGroup:getRealTargets(data.tos)
      local targets = room:getUseExtraTargets(data, false, false)
      local tos = room:askForChoosePlayers(player, targets, 1, 2,
      "#ce_hc__wushuang_zr-choose:::"..data.card:toLogString(), self.name, true)
      if #tos > 0 then
        self.cost_data = {tos = tos}
        return true
      end
    else
      self.cost_data = {tos = event == fk.TargetSpecified and {data.to} or {data.from}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.AfterCardTargetDeclared then
      table.insertTable(data.tos, table.map(self.cost_data.tos, function (p)
        return {p}
      end))
    else
      data.fixedResponseTimes = data.fixedResponseTimes or {}
      if data.card.trueName == "slash" then
        data.fixedResponseTimes["jink"] = 2
      else
        data.fixedResponseTimes["slash"] = 2
        data.fixedAddTimesResponsors = data.fixedAddTimesResponsors or {}
        table.insert(data.fixedAddTimesResponsors, (event == fk.TargetSpecified and data.to or data.from))
      end
    end
  end,
}

lvlingqi:addSkill("ty_hc__guowu")
lvlingqi:addSkill(zhuangrong)
shenwei:addRelatedSkill(shenwei_maxcards)
lvlingqi:addSkill(shenwei)
lvlingqi:addRelatedSkill(wushuangZR)

Fk:loadTranslationTable{
  ["ce_hc_heg__lvlingqi"] = "吕玲绮",
  ["#ce_hc_heg__lvlingqi"] = "无双虓姬",
  --["designer:ce_hc_heg__lvlingqi"] = "xat1k",
  ["illustrator:ce_hc_heg__lvlingqi"] = "君桓文化",

  ["ce_hc__zhuangrong"] = "妆戎",
  [":ce_hc__zhuangrong"] = "出牌阶段限一次，你可以弃置一张锦囊牌，然后获得“无双”至此阶段结束。",
  ["@@ce_hc__zhuanrong_hs_wushuang-phase"] = "无双",
  ["ce_hc__shenwei"] = "神威",
  [":ce_hc__shenwei"] = "主将技，此武将牌上单独的阴阳鱼个数-1；摸牌阶段，若你的体力值为全场最高，你多摸两张牌；你的手牌上限+2。",
  ["ce_hc__wushuang_zr"] = "无双",
  [":ce_hc__wushuang_zr"] = "锁定技，当你使用【杀】指定目标后，该角色需依次使用两张【闪】才能抵消此【杀】；当你使用【决斗】指定目标后，或成为【决斗】的目标后，该角色每次响应此【决斗】需依次打出两张【杀】；你使用非转化的【决斗】的目标上限+2。",
  ["#ce_hc__wushuang_zr-choose"] = "无双：你可以为 %arg 增加至多两个目标",


  ["$ce_hc__shenwei1"] = "锋镝鸣手中，锐戟映秋霜。",
  ["$ce_hc__shenwei2"] = "红妆非我愿，学武觅封侯。",
  ["$ce_hc__zhuangrong1"] = "继父神威，无坚不摧！",
  ["$ce_hc__zhuangrong2"] = "我乃温侯吕奉先之女！",
  ["$ce_hc__wushuang_zr1"] = "猛将策良骥，长戟破敌营。",
  ["$ce_hc__wushuang_zr2"] = "杀气腾剑戟，严风卷戎装。",
  ["~ce_hc_heg__lvlingqi"] = "父亲，女儿好累……",
}

local nanhualaoxian = General(extension, "le_hc_heg__nanhualaoxian", "qun", 3)

local gongxiu = fk.CreateTriggerSkill{
  name = "le_hc__gongxiu",
  anim_type = "offensive",
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.n > 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data, "#le_hc__gongxiu_" .. player:getMark("le_hc__gongxiu") .. "-ask:::" .. player.maxHp)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.n = data.n - 1
    local choices = {}
    if player:getMark("le_hc__gongxiu") ~= 1 then
      table.insert(choices, "le_hc__gongxiu_draw:::" .. player.maxHp)
    end
    if player:getMark("le_hc__gongxiu") ~= 2 then
      table.insert(choices, "le_hc__gongxiu_discard:::" .. player.maxHp)
    end 
    local choice = room:askForChoice(player, choices, self.name, "#le_hc__gongxiu-choice")
    local targets, tos
    if choice:startsWith("le_hc__gongxiu_draw") then
      room:setPlayerMark(player, "le_hc__gongxiu", 1)
      targets = table.map(room.alive_players, Util.IdMapper)
      tos = room:askForChoosePlayers(player, targets, 1, player.maxHp, "#le_hc__gongxiu_draw-choose:::" .. player.maxHp, self.name, false)
      room:sortPlayersByAction(tos)
      for _, id in ipairs(tos) do
        local p = room:getPlayerById(id)
        if not p.dead then
          p:drawCards(1, self.name)
        end
      end
    else
      room:setPlayerMark(player, "le_hc__gongxiu", 2)
      targets = table.map(table.filter(room.alive_players,  function(p) return not p:isNude() end), Util.IdMapper)
      tos = room:askForChoosePlayers(player, targets, 1, player.maxHp, "#le_hc__gongxiu_discard-choose:::" .. player.maxHp, self.name, false)
      room:sortPlayersByAction(tos)
      for _, id in ipairs(tos) do
        local p = room:getPlayerById(id)
        if not p.dead and not p:isNude() then
          room:askForDiscard(p, 1, 1, true, self.name, false)
        end
      end
    end
  end,
}

local jinghe = fk.CreateActiveSkill{
  name = "le_hc__jinghe",
  anim_type = "support",
  target_num = 0,
  card_num = 0,
  max_phase_use_time = 1,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local skills = table.random({"le_hc__leiji", "le_hc__yinbingn", "le_hc__huoqi", "le_hc__guizhu", "le_hc__xianshou", "le_hc__lundao", "le_hc__guanyue", "le_hc__yanzhengn"}, 1)
    local targets = table.map(room.alive_players, Util.IdMapper)
    if #targets == 0 then return end
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#le_hc__jinghe:::" .. skills[1], self.name, false)
    if #tos == 0 then return end
    local to = room:getPlayerById(tos[1])
    if to:hasSkill(skills[1], true, true) then return end
    room:addTableMark(player, self.name, {tos[1], skills[1]})
    room:addTableMark(to, "@le_hc__jinghe", skills[1])
    room:handleAddLoseSkills(to, skills[1], nil, true, false)
  end,
}

local jinghe_trigger = fk.CreateTriggerSkill {
  name = "#le_hc__jinghe_trigger",
  mute = true,
  events = {fk.TurnStart, fk.Death},
  can_trigger = function(self, event, target, player, data)
    return target == player and #player:getTableMark("le_hc__jinghe") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, table in ipairs(player:getTableMark("le_hc__jinghe")) do
      local p = room:getPlayerById(table[1])
      room:removeTableMark(p, "@le_hc__jinghe", table[2])
      room:handleAddLoseSkills(p, "-"..table[2], nil, true, false)
    end
    room:setPlayerMark(player, "le_hc__jinghe", 0)
  end,
}

local taidan = fk.CreateTriggerSkill{
  name = "le_hc__taidan",
  events = {fk.DamageInflicted},
  frequency = Skill.Compulsory,
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasShownSkill(self) and not player:getEquipment(Card.SubtypeArmor)
    and Fk.skills["#peace_spell_skill"] ~= nil and Fk.skills["#peace_spell_skill"]:isEffectable(player) and data.damageType ~= fk.NormalDamage
  end,
  on_use = function(self, event, target, player, data)
    return true
  end,
}
local taidan_maxcards = fk.CreateMaxCardsSkill{
  name = "#le_hc__taidan_maxcards",
  correct_func = function(self, player)
    if player:hasShownSkill("le_hc__taidan") and not player:getEquipment(Card.SubtypeArmor)
    and Fk.skills["#peace_spell_skill"] ~= nil and Fk.skills["#peace_spell_skill"]:isEffectable(player) then
      if player.kingdom == "unknown" then
        return 1
      else
        local num = H.getSameKingdomPlayersNum(Fk:currentRoom(), player)
        return (num or 0) + #player:getPile("heavenly_army")
      end
    end
  end,
}

local le_hc__leiji = fk.CreateTriggerSkill{
  name = "le_hc__leiji",
  anim_type = "offensive",
  events = {fk.CardUsing, fk.CardResponding},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and data.card.name == "jink"
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player, false), Util.IdMapper), 1, 1, "#le_hc__leiji-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(self.cost_data)
    local judge = {
      who = tar,
      reason = self.name,
      pattern = ".|.|spade",
    }
    room:judge(judge)
    if judge.card.suit == Card.Spade then
      room:damage{
        from = player,
        to = tar,
        damage = 2,
        damageType = fk.ThunderDamage,
        skillName = self.name,
      }
    end
end,
}
local le_hc__yinbingn = fk.CreateTriggerSkill{
  name = "le_hc__yinbingn",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.PreDamage, fk.HpLost},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.PreDamage then
        return target == player and data.card and data.card.trueName == "slash"
      else
        return target ~= player
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.PreDamage then
      room:loseHp(data.to, data.damage, self.name)
      return true
    else
      player:drawCards(1, self.name)
    end
  end,
}
local le_hc__huoqi = fk.CreateActiveSkill{
  name = "le_hc__huoqi",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  prompt = "#le_hc__huoqi",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isNude()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  target_filter = function(self, to_select, selected)
    if #selected == 0 then
      local target = Fk:currentRoom():getPlayerById(to_select)
      return target:isWounded() and table.every(Fk:currentRoom().alive_players, function(p) return target.hp <= p.hp end)
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    if target:isWounded() then
      room:recover({
        who = target,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
    if not target.dead then
      target:drawCards(1, self.name)
    end
  end,
}
local le_hc__guizhu = fk.CreateTriggerSkill{
  name = "le_hc__guizhu",
  anim_type = "drawcard",
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(2, self.name)
  end,
}
local le_hc__xianshou = fk.CreateActiveSkill{
  name = "le_hc__xianshou",
  anim_type = "support",
  card_num = 0,
  target_num = 1,
  prompt = "#le_hc__xianshou",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local n = not target:isWounded() and 2 or 1
    target:drawCards(n, self.name)
  end
}
local le_hc__lundao = fk.CreateTriggerSkill{
  name = "le_hc__lundao",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and not data.from.dead and
      data.from:getHandcardNum() ~= player:getHandcardNum()
  end,
  on_cost = function(self, event, target, player, data)
    if data.from:getHandcardNum() > player:getHandcardNum() then
      return player.room:askForSkillInvoke(player, self.name, nil, "#le_hc__lundao-invoke::"..data.from.id)
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local from = data.from
    if data.from:getHandcardNum() > player:getHandcardNum() then
      room:doIndicate(player.id, {from.id})
      local id = room:askForCardChosen(player, from, "he", self.name)
      room:throwCard({id}, self.name, from, player)
    else
      player:drawCards(1, self.name)
    end
  end
}
local le_hc__guanyue = fk.CreateTriggerSkill{
  name = "le_hc__guanyue",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = U.turnOverCardsFromDrawPile(player, 2, self.name, false)
    local result = room:askForGuanxing(player, cards, {1, 2}, {1, 1}, self.name, true, {"Top", "prey"})
    room:sendLog{
      type = "#GuanxingResult",
      from = player.id,
      arg = 1,
      arg2 = 0,
    }
    if #result.top > 0 then
      room:moveCardTo(result.top, Card.DrawPile, nil, fk.ReasonPut, self.name, nil, false, player.id, nil, player.id)
    end
    if #result.bottom > 0 then
      room:obtainCard(player.id, result.bottom[1], false, fk.ReasonJustMove)
    end
  end,
}
local le_hc__yanzhengn = fk.CreateTriggerSkill{
  name = "le_hc__yanzhengn",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and player:getHandcardNum() > 1
  end,
  on_cost = function(self, event, target, player, data)
    local targets = table.map(player.room.alive_players, Util.IdMapper)
    local card = player.room:askForCard(player, 1, 1, false, self.name, true, ".", "#le_hc__yanzhengn-invoke")
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ids = player:getCardIds("h")
    table.removeOne(ids, self.cost_data[1])
    local count = #(room.logic.event_recorder[GameEvent.MoveCards] or Util.DummyTable)
    room:throwCard(ids, self.name, player, player)
    local n = 0
    local e = HC.GetRecentMoveEventByskill(room, self.name, count)
      if e then
        for _, move in ipairs(e.data) do
          n = n + #move.moveInfo
        end
      end
    local targets = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, n, "#le_hc__yanzhengn-choose:::"..n, self.name, false)
    room:sortPlayersByAction(targets)
    for _, id in ipairs(targets) do
      local p = room:getPlayerById(id)
      if not p.dead then
        room:damage{
          from = player,
          to = p,
          damage = 1,
          skillName = self.name,
        }
      end
    end
  end,
}

jinghe:addRelatedSkill(jinghe_trigger)
taidan:addRelatedSkill(taidan_maxcards)

nanhualaoxian:addSkill(gongxiu)
nanhualaoxian:addSkill(jinghe)
nanhualaoxian:addSkill(taidan)
nanhualaoxian:addRelatedSkill(le_hc__leiji)
nanhualaoxian:addRelatedSkill(le_hc__yinbingn)
nanhualaoxian:addRelatedSkill(le_hc__huoqi)
nanhualaoxian:addRelatedSkill(le_hc__guizhu)
nanhualaoxian:addRelatedSkill(le_hc__xianshou)
nanhualaoxian:addRelatedSkill(le_hc__lundao)
nanhualaoxian:addRelatedSkill(le_hc__guanyue)
nanhualaoxian:addRelatedSkill(le_hc__yanzhengn)

Fk:loadTranslationTable{
  ["le_hc_heg__nanhualaoxian"] = "南华老仙",
  ["#le_hc_heg__nanhualaoxian"] = "虚步太清",
  ["illustrator:le_hc_heg__nanhualaoxian"] = "君桓文化",

  ["le_hc__gongxiu"] = "共修",
  [":le_hc__gongxiu"] = "摸牌阶段，你可少摸一张牌，然后选择一项：1.令至多X名角色各摸一张牌；"..
  "2.令至多X名角色各弃置一张牌。（X为你的体力上限，不能连续选择同一项）",

  ["le_hc__jinghe"] = "经合",
  [":le_hc__jinghe"] = "出牌阶段限一次，你可以从“写满技能的天书”中随机选择一个技能，令一名角色获得之直到你下回合开始。",
  ["le_hc__taidan"] = "太丹",
  [":le_hc__taidan"] = "锁定技，若你的装备区没有防具牌，则你视为装备着【太平要术】。",

  ["#le_hc__gongxiu-choice"] = "共修：选择令角色摸牌或弃牌",
  ["#le_hc__gongxiu_0-ask"] = "是否发动 共修，令至多%arg名角色各摸一张牌或各弃置一张牌",
  ["#le_hc__gongxiu_1-ask"] = "是否发动 共修，令至多%arg名角色各弃置一张牌",
  ["#le_hc__gongxiu_2-ask"] = "是否发动 共修，令至多%arg名角色各摸一张牌",
  ["le_hc__gongxiu_draw"] = "令至多%arg名角色各摸一张牌",
  ["le_hc__gongxiu_discard"] = "令至多%arg名角色各弃置一张牌",
  ["#le_hc__gongxiu_draw-choose"] = "共修：选择至多%arg名角色各摸一张牌",
  ["#le_hc__gongxiu_discard-choose"] = "共修：选择至多%arg名角色各弃置一张牌",
  ["#le_hc__jinghe"] = "经合：选择一名角色，令其获得 〖%arg〗",
  ["@le_hc__jinghe"] = "经合",

  ["le_hc__leiji"] = "雷击",
  [":le_hc__leiji"] = "当你使用或打出【闪】时，你可以令一名其他角色进行一次判定，若结果为：♠，你对其造成2点雷电伤害。",
  ["#le_hc__leiji-choose"] = "雷击：令一名角色进行判定，若为♠，你对其造成2点雷电伤害。",
  ["le_hc__yinbingn"] = "阴兵",
  [":le_hc__yinbingn"] = "锁定技，你使用【杀】即将造成的伤害视为失去体力。当其他角色失去体力后，你摸一张牌。",
  ["le_hc__huoqi"] = "活气",
  [":le_hc__huoqi"] = "出牌阶段限一次，你可以弃置一张牌，然后令一名体力最少的角色回复1点体力并摸一张牌。",
  ["#le_hc__huoqi"] = "活气：弃置一张牌，令一名体力最少的角色回复1点体力并摸一张牌",
  ["le_hc__guizhu"] = "鬼助",
  [":le_hc__guizhu"] = "每回合限一次，当一名角色进入濒死状态时，你可以摸两张牌。",
  ["le_hc__xianshou"] = "仙授",
  [":le_hc__xianshou"] = "出牌阶段限一次，你可以令一名角色摸一张牌。若其未受伤，则多摸一张牌。",
  ["#le_hc__xianshou"] = "仙授：令一名角色摸一张牌，若其未受伤则多摸一张牌",
  ["le_hc__lundao"] = "论道",
  [":le_hc__lundao"] = "当你受到伤害后，若伤害来源的手牌多于你，你可以弃置其一张牌；若伤害来源的手牌数少于你，你摸一张牌。",
  ["#le_hc__lundao-invoke"] = "论道：你可以弃置 %dest 一张牌",
  ["le_hc__guanyue"] = "观月",
  [":le_hc__guanyue"] = "结束阶段，你可以观看牌堆顶的两张牌，然后获得其中一张，将另一张置于牌堆顶。",
  ["prey"] = "获得",
  ["le_hc__yanzhengn"] = "言政",
  [":le_hc__yanzhengn"] = "准备阶段，若你的手牌数大于1，你可以选择一张手牌并弃置其余的牌，然后对至多等于弃置牌数的角色各造成1点伤害。",
  ["#le_hc__yanzhengn-invoke"] = "言政：你可以选择保留一张手牌，弃置其余的手牌",
  ["#le_hc__yanzhengn-choose"] = "言政：你可以选择对至多%arg名角色各造成一点伤害",


  ["$le_hc__gongxiu1"] = "福祸与共，业山可移。",
  ["$le_hc__gongxiu2"] = "修行退智，遂之道也。",
  ["$le_hc__jinghe1"] = "大哉乾元，万物资始。",
  ["$le_hc__jinghe2"] = "无极之外，复无无极。",
  ["$le_hc__taidan1"] = "天地万法，皆在此书之中。",
  ["$le_hc__taidan2"] = "天书非凡物，字字皆玄机。",

  ["~le_hc_heg__nanhualaoxian"] = "道亦有穷时……",
}

local zhanglu = General(extension, "ce_hc_heg__n_zhanglu", "wei", 3)

local bushi = fk.CreateTriggerSkill{
  name = "ce_hc__bushi",
  mute = true,
  events = {fk.Damage, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or player ~= target then return end
    if event == fk.Damage then
      return not data.to.dead or H.getKingdomPlayersNum(player.room, false)[H.getKingdom(data.to)] > 0
    else
      return true
    end
  end,
  on_trigger = function (self, event, target, player, data)
    local n = event == fk.Damaged and data.damage or 1
    for i = 1, n, 1 do
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.Damage then
      self.cost_data = {tos = {data.to.id}}
      return true
    else
      local room = player.room
      local targets = table.filter(room.alive_players, function (p)
        return H.compareKingdomWith(p, player)
      end)
      local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#ce_hc__bushi-cancelable", self.name)
      if #tos > 0 then
        self.cost_data = {tos = tos}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:broadcastSkillInvoke(self.name)
    local room = player.room
    if event == fk.Damage then
      room:notifySkillInvoked(player, self.name, "negative", self.cost_data.tos)
      local targets = table.map(table.filter(room.alive_players, function (p)
        return H.compareKingdomWith(p, data.to)
      end), Util.IdMapper)
      local tos = targets
      if #tos > 1 then
        tos = room:askForChoosePlayers(player, targets, 1, 1, "#ce_hc__bushi", self.name, false)
      end
      if #tos > 0 then
        self.cost_data = {tos = tos}
      end
    else
      room:notifySkillInvoked(player, self.name, "masochism", self.cost_data.tos)
    end
    room:getPlayerById(self.cost_data.tos[1]):drawCards(1, self.name)
  end,
}

local midao = fk.CreateTriggerSkill{
  name = "ce_hc__midao",
  events = {fk.TargetSpecifying},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(player, target) and data.firstTarget and target.phase == Player.Play and
      player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and
      (data.card.trueName == "slash" or data.card:isCommonTrick() and data.card.is_damage_card) and
      (target == player or player:hasShownSkill(self) and not target:isKongcheng())
  end,
  on_cost = function (self, event, target, player, data)
    if player == target then
      self.cost_data = nil
      return player.room:askForSkillInvoke(player, self.name)
    else
      local cards = player.room:askForCard(target, 1, 1, false, self.name, true, ".", "#ce_hc__midao:"..player.id)
      if #cards > 0 then
        self.cost_data = cards
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data then
      room:obtainCard(player, self.cost_data, false, fk.ReasonGive, target.id, self.name)
    end
    if player.dead then return end
    local suit = room:askForChoice(player, {"log_spade", "log_heart", "log_club", "log_diamond"}, self.name)
    room:sendLog{
      type = "#ce_hc__midao-suit",
      from = player.id,
      arg = suit,
      toast = true,
    }
    local type = room:askForChoice(player, {"ce_hc__midao-normal", "ce_hc__midao-thunder", "ce_hc__midao-fire"}, self.name)
    room:sendLog{
      type = "#ce_hc__midao-type",
      from = player.id,
      arg = type,
      toast = true,
    }
    local damagetype = fk.NormalDamage
    if type == "ce_hc__midao-thunder" then
      damagetype = fk.ThunderDamage
    elseif type == "ce_hc__midao-fire" then
      damagetype = fk.FireDamage
    end
    local name = data.card.name
    if name:find("slash") then
      if type == "ce_hc__midao-normal" then
        name = "slash"
      elseif type == "ce_hc__midao-thunder" then
        name = "thunder__slash"
      elseif type == "ce_hc__midao-fire" then
        name = "fire__slash"
      end
    end
    local card = Fk:cloneCard(name, U.ConvertSuit(suit, "sym", "int"), data.card.number)
    for k, v in pairs(data.card) do
      if card[k] == nil then
        card[k] = v
      end
    end
    if data.card:isVirtual() then
      card.subcards = data.card.subcards
    else
      card.id = data.card.id
    end
    card.skillNames = data.card.skillNames
    card.skillName = self.name
    card.mark = data.card.mark
    local usedata = room.logic:getCurrentEvent():findParent(GameEvent.UseCard).data[1]
    data.card = card
    usedata.card = card
    data.extra_data = data.extra_data or {}
    data.extra_data.ce_hc__midaotype = damagetype
  end,

  refresh_events = {fk.PreDamage},
  can_refresh = function (self, event, target, player, data)
    if data.card and table.contains(data.card.skillNames, self.name) then
      local e = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
      if e then
        local use = e.data[1]
        return use.extra_data and use.extra_data.ce_hc__midaotype
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local e = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if e then
      local use = e.data[1]
      data.damageType = use.extra_data.ce_hc__midaotype
    end
  end,
}

zhanglu.subkingdom = "qun"
zhanglu:addSkill(bushi)
zhanglu:addSkill(midao)

Fk:loadTranslationTable{
  ["ce_hc_heg__n_zhanglu"] = "张鲁",
  ["#ce_hc_heg__n_zhanglu"] = "政宽教惠",
  ["illustrator:ce_hc_heg__n_zhanglu"] = "磐蒲",

  ["ce_hc__bushi"] = "布施",
  [":ce_hc__bushi"] = "当你受到1点伤害后，你可以令与你势力相同的一名角色摸一张牌；当你对其他角色造成伤害后，你令与其势力相同的一名角色摸一张牌。",
  ["ce_hc__midao"] = "米道",
  [":ce_hc__midao"] = "与你势力相同的角色出牌阶段内限一次，当其使用【杀】或者伤害类锦囊牌指定目标时，其可以交给你一张手牌（其为你则跳过此步），"..
    "令你声明一种花色和一种属性，然后此次使用牌的花色与造成伤害的属性视为与你声明的相同。",

  ["#ce_hc__bushi-cancelable"] = "你可发动 布施，令一名与你势力相同的角色摸一张牌",
  ["#ce_hc__bushi"] = "布施：选择一名角色，令其摸一张牌",
  ["#ce_hc__midao"] = "是否发动 %src 的米道，交给其一张牌",
  ["#ce_hc__midao-suit"] = "%from 发动“米道”，将花色改为 %arg",
  ["#ce_hc__midao-type"] = "%from 发动“米道”，将伤害属性改为 %arg",
  ["ce_hc__midao-normal"] = "普通属性",
  ["ce_hc__midao-thunder"] = "雷电属性",
  ["ce_hc__midao-fire"] = "火焰属性",

  ["$ce_hc__bushi1"] = "争斗，永远没有赢家。",
  ["$ce_hc__bushi2"] = "和平，永远没有输家。",
  ["$ce_hc__midao1"] = "恩结天地，法惠八荒。",
  ["$ce_hc__midao2"] = "行五斗米道，可知暖饱。",
  ["~ce_hc_heg__n_zhanglu"] = "唉，义不敌武，道难御兵……",
}

local shixie = General(extension, "ce_hc_heg__n_shixie", "wu", 3)
shixie.subkingdom = "qun"

local biluan = fk.CreateDistanceSkill{
  name = "ce_hc__biluan",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    if to:hasSkill(self) and to:hasShownSkill(self) then
      return math.max(#to.player_cards[Player.Equip],0)
    end
  end,
}

local lixia = fk.CreateTriggerSkill{
  name = "ce_hc__lixia",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and (H.compareKingdomWith(player, target, true) or target.kingdom == "unknown") and target.phase == Player.Start and not target.dead and not target:inMyAttackRange(player)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {target.id})
    local choices = {"ce_hc__lixia_drawcards"}
    if target.hp > 0 and #player:getCardIds(Player.Equip) > 0 then
      table.insert(choices, "ce_hc__lixia_loseHp")
    end
    local choice = room:askForChoice(target, choices, self.name)
    if choice == "ce_hc__lixia_drawcards" then
      player:drawCards(1, self.name)
    elseif choice == "ce_hc__lixia_loseHp" then
      if #player.player_cards[Player.Equip] > 0 then
      local id = room:askForCardChosen(target, player, "e", self.name)
      room:throwCard({id}, self.name, player, target)
      end
      room:loseHp(target, 1, self.name)
    end
  end,
}
shixie:addSkill(biluan)
shixie:addSkill(lixia)

Fk:loadTranslationTable{
  ["ce_hc_heg__n_shixie"] = "士燮",
  ["#ce_hc_heg__n_shixie"] = "百粤灵欹",
  ["illustrator:ce_hc_heg__n_shixie"] = "磐蒲",

  ["ce_hc__biluan"] = "避乱",
  [":ce_hc__biluan"] = "锁定技，其他角色计算与你的距离+X（X为你装备区内的牌数）。",
  ["ce_hc__lixia"] = "礼下",
  [":ce_hc__lixia"] = "锁定技，其他势力角色的准备阶段，若你不在其攻击范围内，其选择一项"..
  "：1.令你摸一张牌；2.弃置你装备区内的一张牌，然后其失去1点体力。",

  ["#ce_hc__lixia-ask"] = "礼下：是否弃置士燮一张装备区内的牌。",
  ["ce_hc__lixia_drawcards"] = "令士燮摸一张牌",
  ["ce_hc__lixia_loseHp"] = "弃置士燮一张装备区内的牌并失去1点体力",

  ["$ce_hc__biluan1"] = "审时度势，以稳求进。",
  ["$ce_hc__biluan2"] = "进退利弊，自当细细思量。",
  ["$ce_hc__lixia1"] = "先生大才，岂可居于人下。",
  ["$ce_hc__lixia2"] = "先生贤才，老夫着实佩服。",
  ["~ce_hc_heg__n_shixie"] = "天命之时……已到……",
}

local pengyang = General(extension, "nos_hc_heg__n_pengyang", "shu", 3)
pengyang.subkingdom = "qun"

local daming = fk.CreateTriggerSkill{
  name = "nos_hc__daming",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Play and H.compareKingdomWith(player, target) and not player:isKongcheng() and not target.dead
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local cards = room:askForDiscard(player, 1, 1, true, self.name, true, ".|.|.|.|.|trick", "#nos_hc__daming-ask", true)
    if #cards > 0 then
      self.cost_data = {cards = cards, tos = {target.id}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.cards, self.name, player)
    if player.dead then return end
    local targets = table.map(table.filter(room.alive_players, function (p) return not p.chained end), Util.IdMapper)
    if #targets > 0 then
      local t = room:askForChoosePlayers(player, targets, 1, 1, "#nos_hc__daming-chain", self.name, false)
      if #t > 0 then
        room:getPlayerById(t[1]):setChainState(true)
      end
    end
    if player.dead then return end
    local chains = {}
    for _, p in ipairs(room.alive_players) do
      if p.chained and p.kingdom ~= "unknown" and not table.find(chains, function (p1) return H.compareKingdomWith(p,p1) end) then
        table.insert(chains, p)
      end
    end
    if #chains > 0 then
      player:drawCards(#chains, self.name)
    end
    if target.dead or player.dead then return end
    local peach, slash = Fk:cloneCard("peach"), Fk:cloneCard("thunder__slash")
    local cancelable = player:canUseTo(peach, target, {fix_targets = {target.id}})
    local victims = table.map(table.filter(room.alive_players, function (p) return target:canUseTo(slash, p, { bypass_times = true }) end), Util.IdMapper)
    if #victims > 0 then
      local v = room:askForChoosePlayers(player, victims, 1, 1, cancelable and "#nos_hc__daming-effect::"..target.id or "#nos_hc__daming-effectslash::"..target.id, self.name, cancelable)
      if #v > 0 then
        local use = { from = target.id, tos = {  v  }, card = slash, extraUse = true, extra_data = { bypass_times = true } }
        room:useCard(use)
        return
      end
    end
    if cancelable then
      local use = { from = player.id, tos = { { target.id } }, card = peach, extra_data = { fix_targets = {target.id} } }
      room:useCard(use)
    end
  end,
}

local xiaoni = fk.CreateTriggerSkill{
  name = "nos_hc__xiaoni",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified, fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    if player ~= target or not player:hasSkill(self) then return end
    if event == fk.TargetSpecified and not data.firstTarget or event == fk.TargetConfirmed and data.from == player.id then return end
    if data.card.trueName ~= "slash" and not data.card:isCommonTrick() then return end
    if H.getSameKingdomPlayersNum(player.room, player) > 1 and not table.find(player.room.alive_players, function (p)
      return H.compareKingdomWith(player, p) and #p:getCardIds(Player.Hand) > #player:getCardIds(Player.Hand)
      end) then
      self.cost_data = {tos = event == fk.TargetSpecified and AimGroup:getAllTargets(data.tos) or {player.id}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, self.name, event == fk.TargetSpecified and "control" or "negative", self.cost_data.tos)
    player:broadcastSkillInvoke(self.name)
    local targets = self.cost_data.tos
    local usedata = room.logic:getCurrentEvent():findParent(GameEvent.UseCard).data[1]
    if #targets > 0 then
      usedata.disresponsiveList = usedata.disresponsiveList or {}
      for _, p in ipairs(targets) do
        table.insertIfNeed(usedata.disresponsiveList, p)
      end
    end
  end,
}

pengyang:addSkill(daming)
pengyang:addSkill(xiaoni)

Fk:loadTranslationTable{
  ["nos_hc_heg__n_pengyang"] = "彭羕",
  ["#nos_hc_heg__n_pengyang"] = "误身的狂士",
  ["illustrator:nos_hc_heg__n_pengyang"] = "匠人绘-零一",

  ["nos_hc__daming"] = "达命",
  [":nos_hc__daming"] = "与你势力相同的角色出牌阶段开始时，你可以弃置一张锦囊牌，横置一名角色，摸X张牌（X为有处于连环状态角色的势力数），然后你选择一项："
    .."1.视为对当前回合角色使用一张【桃】；2.令当前回合角色视为对你选择的另一名角色使用一张雷【杀】（有距离限制）。",
  ["nos_hc__xiaoni"] = "嚣逆",
  [":nos_hc__xiaoni"] = "锁定技，当你使用牌指定目标后，或成为其他角色使用牌的目标后，若场上有与你势力相同的其他角色且你是其中手牌最多的角色，目标角色不能响应此牌。",

  ["#nos_hc__daming-ask"] = "你可以弃置一张锦囊牌发动〖达命〗",
  ["#nos_hc__daming-chain"] = "达命：选择一名角色横置",
  ["#nos_hc__daming-effect"] = "达命：选择%dest视为使用雷【杀】的目标，或点取消视为对%dest使用【桃】",
  ["#nos_hc__daming-effectslash"] = "达命：选择%dest视为使用雷【杀】的目标",

  ["$nos_hc__daming1"] = "孝直溢美之言，特以此小利报之，还望笑纳。",
  ["$nos_hc__daming2"] = "孟起，莫非甘心为他人座下之客。",
  ["$nos_hc__xiaoni1"] = "如此荒辈之徒为主，成何用也。",
  ["$nos_hc__xiaoni2"] = "公既如此，恕在下诚难留之。",
  ["~nos_hc_heg__n_pengyang"] = "人言我心大志寡，难可保安，果然如此，唉……",
}

return extension